package com.yuan.common.action;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.jd.common.web.cookie.CookieUtils;
import com.jd.common.web.result.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.util.ValueStack;
import com.yuan.common.message.InformationMessage;

/**
 * Action的基类
 * 
 * @author Beni
 * 
 */
public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {

	private static final long serialVersionUID = 1L;

	public static final String SUCCESS = "success";

	private CookieUtils cookieUtils;

	protected HttpServletResponse response;
	protected HttpServletRequest request;

	private InformationMessage informationMessage; // 页面显示的提示信息，异常信息

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public String getCookieValue(String name) {
		return cookieUtils.getCookieValue(request, name);
	}

	/*
	 * 获取真实的IP地址
	 */
	public String getRemoteIP() {
		String ip = request.getRemoteAddr();
		if (request.getHeader("x-forwarded-for") != null
				&& !"unknown".equalsIgnoreCase(request
						.getHeader("x-forwarded-for"))) {
			ip = ip + "," + request.getHeader("x-forwarded-for");
		}
		return ip;
	}

	protected int page;

	public void setPage(int page) {
		if (page <= 0) {
			page = 1;
		}
		this.page = page;
	}

	public int getPage() {
		return page;
	}

	/**
	 * 将result中的值写入值栈 会写入result变量，同时会把reuslt里面map的内容写入。
	 * 对于消息。如果result返回成功，则写入message，否则写入error
	 * 
	 * @param result
	 *            结果
	 */
	protected void toVm(Result result) {

		ValueStack context = ActionContext.getContext().getValueStack();
		context.set("result", result);
		Set<String> set = result.keySet();
		for (String key : set) {
			context.set(key, result.get(key));
		}
		String resultCode = result.getResultCode();
		if (StringUtils.isNotBlank(resultCode)) {
			String text;
			String[] params = result.getResultCodeParams();
			if (params != null && params.length > 0) {
				text = getText(resultCode, params);
			} else {
				text = getText(resultCode);
			}
			if (result.getSuccess()) {
				addActionMessage(text);
			} else {
				addActionError(text);
			}
		}
	}

	public InformationMessage getInformationMessage() {
		return informationMessage;
	}

	public void setInformationMessage(InformationMessage informationMessage) {
		this.informationMessage = informationMessage;
	}

}
